#
# Copyright 2009, Josef Kyrian <josef.kyrian@gmail.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2, or (at your option)
# any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.

import g
from config import config
import os
import Xlib.display
import Xlib.X
import subprocess
from PyQt4 import QtGui, QtCore, Qt
import time
from dbglog import dbg


def getFocusedWindow():
	"""
	"""
	display = Xlib.display.Display()
	focus = display.get_input_focus()
	return focus.focus
#enddef


class CmdThread(QtCore.QThread):
	def __init__(self, cmd):
		QtCore.QThread.__init__(self)
		self.cmd = cmd
	#enddef
	
	def run(self):
		dbg.log("Run command '%s' in thread", self.cmd)
		os.system(self.cmd)
		dbg.log("Command '%s' exited", self.cmd)
		#print cmdexec(self.cmd, runInBackground = False)
	#enddef
#endclass


def cmdexec(cmd, runInBackground = False):
	"""
	Runs cmd and return output
	"""
	if (not runInBackground):
		process = subprocess.Popen(cmd, stdin = subprocess.PIPE, stdout = subprocess.PIPE, stderr = subprocess.PIPE)
		data = process.stdout.read()
		process.wait()
		return data
	else:
		g.runningThreads.append(CmdThread(cmd))
		g.runningThreads[-1].start()
	#endif
#enddef


def isMPlayer(window):
	"""
	Returns if given window is mplayer
	"""
	return window.get_wm_name() and window.get_wm_name().lower().find('mplayer') != -1
#enddef


def isHTPCController(window):
	"""
	Returns if given window is HTPC Controller
	"""
	return window.get_wm_name() and window.get_wm_name().lower().find('htpccontroller') != -1
#enddef


def isMythTv(window):
	"""
	Returns if given window is mplayer
	"""
	return window.get_wm_name() and window.get_wm_name().lower().find('myth') != -1
#enddef


class ShutdownThread(QtCore.QThread):
	def run(self):
		while g.shutdownRemainingTime:
			g.shutdownRemainingTime -= 1
			time.sleep(1)
		#endwhile
		if (g.shutdownRemainingTime != None):
			shutdownHTPC()
		#endif
	#enddef
#endclass


def shutdownHTPC(timeoutSeconds = 0):
	"""
	Shutdowns HTPC
	"""
	dbg.log("Shutdown HTPC in %s seconds", timeoutSeconds)
	if (not timeoutSeconds):
		os.system(config.shutdownCommand)
	else:
		g.shutdownRemainingTime = timeoutSeconds
		g.shutdownThread = ShutdownThread()
		g.shutdownThread.start()
	#endif
#enddef


def rebootHTPC():
	"""
	Reboots HTPC
	"""
	os.system(config.rebootCommand)
#enddef


def cancelShutdownHTPC():
	"""
	Shutdowns HTPC
	"""
	g.shutdownRemainingTime = None
#enddef


def isRunning(programName):
	"""
	Returns weather the program is running
	"""
	cmd = ["bash", "-c", "ps ax | grep %s | grep -v grep" % programName]
	return cmdexec(cmd).strip() != ""
#enddef


def runScreenSaver():
	"""
	Runs screensaver
	"""
	cmdexec(config.screenSaverRunCommand, runInBackground = True)
#enddef


def runFun1():
	"""
	Runs fun1
	"""
	cmdexec(config.funOneRunCommand, runInBackground = True)
#enddef


def stopFun1():
	"""
	Stops fun1
	"""
	cmdexec(config.funOneStopCommand, runInBackground = True)
#enddef


def restartFun1():
	"""
	Restarts fun1
	"""
	cmdexec(config.funOneRestartCommand, runInBackground = True)
#enddef


def runMythTV():
	"""
	Runs MythTV
	"""
	cmdexec(config.mythTvRunCommand, runInBackground = True)
#enddef


def restartMythTV():
	"""
	Restarts MythTV
	"""
	cmdexec(config.mythTvRestartCommand, runInBackground = True)
#enddef


def restartMythTVBackend():
	"""
	Restarts MythTVBackend
	"""
	cmdexec(config.mythTvBackendRestartCommand, runInBackground = True)
#enddef


def getShutdownRemainingTime():
	"""
	Returns remaining time to shutdown
	"""
	if (g.shutdownRemainingTime == None):
		return None
	else:
		minutes = g.shutdownRemainingTime / 60
		seconds = g.shutdownRemainingTime % 60
		return '%s min %s sec' % (minutes, seconds)
	#endif
#enddef


def increaseVolume():
	"""
	Increases volume
	"""
	cmdexec(config.volumeIncreaseCommand, runInBackground = True)
#enddef


def decreaseVolume():
	"""
	Decreases volume
	"""
	cmdexec(config.volumeDecreaseCommand, runInBackground = True)
#enddef
